﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace AutoDeployForSims.Model
{
    public  class CallOutAppModel
    {
        [DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

        enum ShowCommands
        {
            SW_HIDE = 0,
            SW_NORMAL = 1,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
        }

        public void ShowApp(string appname, string appPath)
        {
            IntPtr OtherExeWnd = FindWindow(null, appname);
            //判断这个窗体是否有效
            if (OtherExeWnd != IntPtr.Zero)
            {
                int retInt = ShowWindow(OtherExeWnd, 10);
                if (retInt > 0)
                {
                    Process[] processes = Process.GetProcessesByName(appname);
                    if (processes.Length > 0)
                    {
                        int processId = processes[0].Id;
                        WindowActivator.ActivateProcessWindow(processId);
                    }
                }
            }
            else
            {
                //判断是否启动
                Process[] processes = Process.GetProcessesByName(appname);
                if (processes.Length > 0)
                {
                    WindowActivator.ActivateProcessWindow(processes[0].Id);
                }
                else
                {
                    //打开
                    OpenApp(appPath);
                }
            }


        }
        private void OpenApp(string appPath)
        {
            //ShellExecute(IntPtr.Zero, "", appPath, "", "", ShowCommands.SW_SHOW);
            Process.Start(appPath);
        }
        public void CloseApp(string appname)
        {
            
            // 获取所有与processName匹配的进程
            Process[] processes = Process.GetProcessesByName(appname);

            foreach (Process process in processes)
            {
                try
                {
                    // 关闭进程
                    process.Kill(); // 使用Kill方法强制关闭进程
                    Console.WriteLine($"进程 {process.Id} ({process.ProcessName}) 已被关闭。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法关闭进程 {process.Id}: {ex.Message}");
                }
            }
        }

    }
}
